package org.meetunexpectedly.service.login.impl;

import lombok.extern.slf4j.Slf4j;
import org.meetunexpectedly.constant.RedisConstant;
import org.meetunexpectedly.entity.vo.Captcha;
import org.meetunexpectedly.exception.BaseException;
import org.meetunexpectedly.service.login.CaptchaService;
import org.meetunexpectedly.service.login.EmailService;
import org.meetunexpectedly.util.CaptchaUtil;
import org.meetunexpectedly.util.RedisCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Map;

/**
 * @Description: 图形验证码服务实现类
 * @Author: pupil
 * @Date: 2024/08/04 下午 8:26
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private CaptchaUtil captchaUtil;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private EmailService emailService;

    @Override
    public BufferedImage getCaptcha(String uuId) {
        Map<Object, Object> map = captchaUtil.getCaptcha();
        String code = (String) map.get(String.class);
        BufferedImage image = (BufferedImage) map.get(BufferedImage.class);
        // 存储到redis中
        redisCacheUtil.set(RedisConstant.CAPTCHA_CODE + uuId, code, RedisConstant.CAPTCHA_CODE_TIME);
        return image;
    }

    @Override
    public Boolean validate(Captcha captcha) throws Exception {
        String uuId = captcha.getUuid();
        String email = captcha.getEmail();
        String inPutCode = captcha.getCode();

        // 判断uuId是否传入
        if (uuId == null) {
            throw new BaseException("uuId为空");
        }
        // 根据uuid查询出redis中对应的图形验证码
        String code = (String) redisCacheUtil.get(RedisConstant.CAPTCHA_CODE + uuId);

        // 判断验证码是否失效
        if (code == null) {
            throw new BaseException("图形验证码已失效");
        }

        // 查询成功后删除对应的图形验证码
        redisCacheUtil.del(RedisConstant.CAPTCHA_CODE + uuId);

        if (!code.equals(inPutCode)) {
            throw new BaseException("图形验证码错误");
        }

        code = captchaUtil.getCode();
        redisCacheUtil.set(RedisConstant.EMAIL_CODE + email, code, RedisConstant.EMAIL_CODE_TIME);
        String message = captcha.getModel().equals("0") ? "注册验证码：" + code + "  ,验证码5分钟之内有效" : "忘记密码验证码：" + code + "  ,验证码5分钟之内有效";
        emailService.send(email, message);

        return true;
    }


}
